package com.example.zhongshuishi.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.example.zhongshuishi.controller.AliyunSmsConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SmsService {

    private final AliyunSmsConfig smsConfig;
    private final StringRedisTemplate redisTemplate;

    private String generateCode() {
        return String.valueOf(new Random().nextInt(8999) + 1000);
    }

    public boolean sendSmsCode(String phoneNumber) {
        try {
            String code = generateCode();


            IAcsClient client = new DefaultAcsClient(
                    DefaultProfile.getProfile("cn-hangzhou",
                            smsConfig.getAccessKeyId(),
                            smsConfig.getAccessKeySecret()));

            // 构建请求
            CommonRequest request = new CommonRequest();
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.putQueryParameter("PhoneNumbers", phoneNumber);
            request.putQueryParameter("SignName", smsConfig.getSignName());
            request.putQueryParameter("TemplateCode", smsConfig.getTemplateCode());
            request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

            // 发送请求
            CommonResponse commonResponse = client.getCommonResponse(request);

            // 处理响应
            if (commonResponse.getHttpStatus() == 200) {
                redisTemplate.opsForValue().set(
                        "sms:code:" + phoneNumber,
                        code,
                        5, TimeUnit.DAYS.MINUTES
                );
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // 验证验证码
    public boolean verifyCode(String phoneNumber, String code) {
        String storedCode = redisTemplate.opsForValue()
                .get("sms:code:" + phoneNumber);
        return code.equals(storedCode);
    }
}